package tralala.client.gui;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.rmi.RemoteException;
import java.util.ArrayList;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import tralala.client.controller.TralalaController;
import tralala.server.data.dto.CancionDTO;



public class Window extends JDialog implements ActionListener, MouseListener {
	
	private static final long serialVersionUID = -7461719037402108362L;
	private JTable jtResult;
	private TableModelSearch tmResult;
	private JScrollPane jsScroll;
	private JPanel jpSup;
	private JPanel jpMid;
	private JPanel jpInf;
	private JTextField jtTitulo;
	private JTextField jtArtista;
	private JButton jbSearch;
	private JButton jbCancel;
	private TableRowSorter<TableModel> trSort;
	private JLabel jlnoResult;
	private CardLayout cl;
	private TralalaController controller;
	
	public Window(TralalaController controller) {
		
		this.controller = controller;
		jpSup = new JPanel();
		jpInf = new JPanel();
		jpMid = new JPanel();
		
		jlnoResult = new JLabel("No se han encontrado resultados.");
		
		jtTitulo = new JTextField(12) {
			private static final long serialVersionUID = -7461719037402108362L;
			public String getText() {
				String tempString = super.getText();
				if (tempString.equals(""))
					return null;
				else
					return tempString;
			}
		};
		jtArtista = new JTextField(10) {
			private static final long serialVersionUID = -7461719037402108362L;
			public String getText() {
				String tempString = super.getText();
				if (tempString.equals(""))
					return null;
				else
					return tempString;
			}
		};
		
		
		String[] columTitulos = {"Nick", "Titulo", "Artista", "Email"};;
	    jbSearch = new JButton("Buscar");
		jbCancel = new JButton("Volver");
		tmResult = new TableModelSearch(0, 6);
		trSort = new TableRowSorter<TableModel>(tmResult);
		tmResult.setColumnIdentifiers(columTitulos);
		jtResult = new JTable(tmResult);
		jsScroll = new JScrollPane(jtResult);
		
		// Layouts
		jpInf.setLayout(new FlowLayout());
		jpSup.setLayout(new FlowLayout());
		jpMid.setLayout(new CardLayout());
		cl = (CardLayout)(jpMid.getLayout());
		getContentPane().setLayout(new BorderLayout());

		// Add components
		jpSup.add(addComponent("Titulo: ", jtTitulo, true));
		jpSup.add(addComponent("Artista: ", jtArtista, true));
		jpInf.add(jbSearch);
		jpInf.add(jbCancel);
		jpMid.add(jsScroll, "Result");
		jpMid.add(jlnoResult, "No results");
		getContentPane().add(jpSup, BorderLayout.NORTH);
		getContentPane().add(jpMid, BorderLayout.CENTER);
		getContentPane().add(jpInf, BorderLayout.SOUTH);
		getContentPane().add(Box.createRigidArea(new Dimension(10, 0)), BorderLayout.EAST);
		getContentPane().add(Box.createRigidArea(new Dimension(10, 0)), BorderLayout.WEST);

		// Listeners
		jbSearch.addActionListener(this);
		jbCancel.addActionListener(this);
		jtResult.addMouseListener(this);
		//Sorting
		jtResult.setRowSorter(trSort);
		cl.show(jpMid, "Result");
		// Window characteristics
		this.setSize(550, 600);
		this.setTitle("Search");
		this.setResizable(true);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.setVisible(true);
	}

	private JPanel addComponent(String nom, JComponent comp, boolean order) {
		JLabel tempLabel = new JLabel(nom);
		JPanel tempPanel = new JPanel();
		tempPanel.setLayout(new FlowLayout());
		if (order) {
			tempPanel.add(tempLabel);
			tempPanel.add(comp);
		} else {
			tempPanel.add(comp);
			tempPanel.add(tempLabel);
		}
		return tempPanel;
	}
	
	private void anyadirCanciones(ArrayList<CancionDTO> canciones) {
		if(canciones == null) {
			cl.show(jpMid, "No results");
		} else {
			for(CancionDTO tempUser : canciones) {
				tmResult.anyadirColumna(tempUser);
			}
		}
	}


	public void actionPerformed(ActionEvent e) {
		
		Object botonPulsado = e.getSource();

		if (botonPulsado == jbSearch) {
			new Thread(new Runnable() {
				public void run() {
					try {
						 // If any JTextField is different from null
						if (jtTitulo.getText() != null || jtArtista.getText() != null) {
							cl.show(jpMid, "Result");
							jtTitulo.setBackground(Color.WHITE);
							jtArtista.setBackground(Color.WHITE);
							ArrayList<CancionDTO> canciones = controller.buscar(jtTitulo.getText(), jtArtista.getText());
							tmResult.borrar();
							anyadirCanciones(canciones);
						} else {
							tmResult.borrar();
							jtTitulo.setBackground(Color.RED);
							jtArtista.setBackground(Color.RED);
						    cl.show(jpMid, "No results");
						}
					} catch (RemoteException e) {
						//logger.error("Error: " + e.getMessage(), e);
					}
				}
			}).start();

		} else if (botonPulsado == jbCancel) {
			this.setVisible(false);
			this.dispose();
		}
	}
	
	public void mouseClicked(MouseEvent e) {
	      if (e.getClickCount() == 2) {
	         JTable target = (JTable)e.getSource();
	         int row = target.getSelectedRow();
	         controller.abrirRepr(tmResult.getTitulo(row));
	         this.setVisible(false);
	         this.dispose();
	      }
	}
	
	@Override
	public void mouseReleased(MouseEvent e) {
	}
	
	@Override
	public void mouseEntered(MouseEvent e) {
	}
	
	@Override
	public void mousePressed(MouseEvent e) {
	}
	
	@Override
	public void mouseExited(MouseEvent e) {
	}
	
	public static void main(String[]args) {
		new Window(null);
	}
}

